﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AFCEPF.BankApplication.BLL
{
    /// <summary>
    /// Base class used for singletons
    /// </summary>
    /// <typeparam name="T">The class type</typeparam>
    public class Singleton<T> where T : class
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        protected Singleton() { }

        #endregion

        #region Private Variables

        private static T _instance = null;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the instance of the singleton
        /// </summary>
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (typeof(T))
                    {
                        ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
                            null, new Type[0], null);

                        if (constructor == null || constructor.IsAssembly)
                        {
                            throw new Exception("Constructor is not private or protected for type " + typeof(T).Name);
                        }
                        _instance = (T)constructor.Invoke(null);
                    }
                }
                return _instance;
            }
        }

        #endregion
    }
}
